#include "protocal.h"
#include "sock.h"
#include <cstring>

void Usage(char *args)
{
    std::cout << "Usage:\n\t" << args << " server.addr server.port" << std::endl;
    exit(0);
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }

    int sock = Sock::sock();
    uint16_t ser_port = atoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(ser_port);
    Sock::Connect(sock, &server);

    
    // int sock = socket(AF_INET, SOCK_STREAM, 0);
    // if (sock < 0)
    // {
    //     std::cerr << "socket failed" << errno << std::endl;
    //     return 1;
    // }
    // std::cout << "socket success" << std::endl;

    // uint16_t ser_port = atoi(argv[2]);
    // std::string ser_addr = argv[1];
    // struct sockaddr_in server;
    // server.sin_family = AF_INET;
    // server.sin_port = htons(ser_port);
    // server.sin_addr.s_addr = INADDR_ANY;
    // // server.sin_addr.s_addr = inet_addr(ser_addr.c_str());

    // if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    // {
    //     std::cerr << "connnect failed" << errno << std::endl;
    //     return 2;
    // }
    // std::cout << "connect success" << std::endl;

    request_t req;
    std::cout << "请输入操作数1:>";
    std::cin >> req.num1;
    std::cout << "请输入操作数2:>";
    std::cin >> req.num2;
    std::cout << "请输入操作符:>";
    std::cin >> req.op;


    //方法1：根据大小写入
    //write(sock, &req, sizeof(req));

    //方法2：定制协议写入
    std::string json_string = SerializeRequest(req);
    write(sock, json_string.c_str(), json_string.size());
    req_result_t res;
    
    //read(sock, &res, sizeof(res));

    char buffer[1024] = {0};
    ssize_t size = read(sock, buffer, sizeof(buffer));
    buffer[size] = 0;
    json_string = buffer;
    DeserializeReqResult(json_string, &res);
    if (res.exit_code == 0)
    {
        std::cout << "result = " << res.result << std::endl;
    }
    else if (res.exit_code == -1)
    {
        std::cout << "出现除零错误" << std::endl;
    }
    else
    {
        std::cout << "取余错误" << std::cout;
    }
}
